package com.learn.geoquiz

import android.app.Activity
import android.app.ActivityOptions
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProviders

// 定义一个 TAG 常量，用于记录日志
private const val TAG = "MainActivity"

private const val KEY_INDEX = "index"

private const val REQUEST_CODE_CHEAT = 0

class MainActivity : AppCompatActivity() {

    // 1. 定义视图变量
    private lateinit var trueButton: Button
    private lateinit var falseButton: Button
    private lateinit var previousButton: ImageButton
    private lateinit var nextButton: ImageButton
    private lateinit var questionTextView: TextView
    private lateinit var cheatButton: Button
    private lateinit var cheatTip: TextView

    private val quizViewModel: QuizViewModel by lazy {
        ViewModelProviders.of(this).get(QuizViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        Log.d(TAG, "onCreate() called")

        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        setTitle(R.string.app_name)

        val currentIndex = savedInstanceState?.getInt(KEY_INDEX, 0) ?: 0
        quizViewModel.currentIndex = currentIndex

        // 2. 通过资源ID访问视图对象
        trueButton = findViewById(R.id.true_button)
        falseButton = findViewById(R.id.false_button)
        previousButton = findViewById(R.id.previous_button)
        nextButton = findViewById(R.id.next_button)
        questionTextView = findViewById(R.id.textView)
        cheatButton = findViewById(R.id.cheat_button)
        cheatTip = findViewById(R.id.cheat_tip)

        updateQuestion()
        updateCheatTip()

        trueButton.setOnClickListener { view: View ->
            // 3.1 处理true按钮的点击事件
            checkAnswer(true)
        }

        falseButton.setOnClickListener { view: View ->
            // 3.2 处理false按钮的点击事件
            checkAnswer(false)
        }
        previousButton.setOnClickListener { view: View ->
            // 3.3 处理previous按钮的点击事件
            quizViewModel.moveToPrevious()
            updateQuestion()
        }

        nextButton.setOnClickListener { view: View ->
            // 3.3 处理next按钮的点击事件
            quizViewModel.moveToNext()
            updateQuestion()
        }

        questionTextView.setOnClickListener { view: View ->
            // 3.4 处理questionTextView的点击事件
            quizViewModel.moveToNext()
            updateQuestion()
        }

        cheatButton.setOnClickListener({ view: View ->

            if (quizViewModel.cheatCount >= quizViewModel.maxCheatCount) {
                Toast.makeText(
                    this,
                    getString(R.string.cheats_limit, quizViewModel.maxCheatCount),
                    Toast.LENGTH_SHORT
                ).show()
                return@setOnClickListener
            }

            Toast.makeText(
                this,
                getString(
                    R.string.cheats_left,
                    quizViewModel.maxCheatCount - quizViewModel.cheatCount
                ),
                Toast.LENGTH_SHORT
            ).show()

            // 3.5 处理cheatButton的点击事件
            // Start CheatActivity
            // 显式调用 CheatActivity
//            val intent = Intent(this, CheatActivity::class.java)
//            startActivity(intent)

            // 启动CheatActivity, 并将答案传递给它
            val intent =
                CheatActivity.newIntent(this@MainActivity, quizViewModel.currentQuestion.answer)
//            startActivity(intent)
//            从子activity获取返回结果
//            startActivityForResult(intent, REQUEST_CODE_CHEAT)

            // 添加动画效果
            //  Build.VERSION.SDK_INT常量代表了Android设备的版本号 只有在 23 及以上的版本才支持动画效果
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val options =
                    ActivityOptions.makeClipRevealAnimation(view, 0, 0, view.width, view.height)
                startActivityForResult(intent, REQUEST_CODE_CHEAT, options.toBundle())
            } else {
                startActivityForResult(intent, REQUEST_CODE_CHEAT)
            }
        })
    }

    // 生命周期方法
    override fun onStart() {
        super.onStart()
        Log.d(TAG, "onStart() called")
    }

    override fun onStop() {
        super.onStop()
        Log.d(TAG, "onStop() called")
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume() called")
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "onPause() called")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy() called")
    }

    override fun onSaveInstanceState(savedInstanceState: Bundle) {
        super.onSaveInstanceState(savedInstanceState)
        Log.i(TAG, "onSaveInstanceState")
        savedInstanceState.putInt(KEY_INDEX, quizViewModel.currentIndex)
    }

    // 处理从CheatActivity返回的结果
    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode != Activity.RESULT_OK) {
            return
        }
        if (requestCode == REQUEST_CODE_CHEAT) {
            val isCheated = data?.getBooleanExtra(EXTRA_ANSWER_SHOWN, false) ?: false

            // 如果用户在CheatActivity中查看了答案，增加作弊次数
            if (isCheated) {
                quizViewModel.cheatCount++
                updateCheatTip()
            }
            // 标记当前问题已作弊
            quizViewModel.currentQuestion.isCheated = isCheated
        }
    }

    // 更新问题文本和按钮状态
    private fun updateQuestion() {
        val questionTextResId = quizViewModel.currentQuestion.textResId
        questionTextView.setText(questionTextResId)

        updateAnswerButtonStatus()
    }

    // 检查用户答案并给出反馈
    private fun checkAnswer(userAnswer: Boolean) {
        val currentQuestion = quizViewModel.currentQuestion
        currentQuestion.isAnswered = true
        currentQuestion.userAnswer = userAnswer

        val messageResId = when {
            quizViewModel.currentQuestion.isCheated -> R.string.judgment_toast
            userAnswer == currentQuestion.answer -> R.string.correct_toast
            else -> R.string.incorrect_toast
        }
        Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show()

        updateAnswerButtonStatus()
        showResult()
    }

    // 更新答题按钮状态
    private fun updateAnswerButtonStatus() {
        val isAnswered = quizViewModel.currentQuestion.isAnswered
        trueButton.isEnabled = !isAnswered
        falseButton.isEnabled = !isAnswered
    }

    // 更新作弊提示和按钮状态
    private fun updateCheatTip() {
        // 更新提示文本
        cheatTip.text =
            getString(R.string.cheats_left, quizViewModel.maxCheatCount - quizViewModel.cheatCount)

        // 当达到最大作弊次数时禁用按钮
        if (quizViewModel.cheatCount >= quizViewModel.maxCheatCount) {
            cheatButton.isEnabled = false
            cheatButton.alpha = 0.5f // 视觉上禁用按钮
        }
    }

    // 显示答题结果评分（挑战练习）
    private fun showResult() {
//        val answeredCount = questionBank.count { it.isAnswered }
//        val correctCount = questionBank.count { it.isAnswered && it.answer == it.userAnswer }
//        if (questionBank.size == answeredCount) {
//            val percentage = (correctCount.toFloat() / answeredCount * 100).toInt()
//            Toast.makeText(
//                this,
//                "所有的问题都已回答：${correctCount}/${questionBank.size} (${percentage} %)",
//                Toast.LENGTH_SHORT
//            ).show()
//        }
    }
}